# -*- coding: UTF-8 -*-
import http.cookiejar, urllib, datetime, time, os.path
class HttpClient(object):
	def __init__(self, cookie_jar):
		self.cookie_jar = http.cookiejar.MozillaCookieJar(cookie_jar)
		if not os.path.exists(cookie_jar):
			self.cookie_jar.save()
		self.cookie_jar.revert(ignore_discard=False, ignore_expires=False)
		self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookie_jar))
		urllib.request.install_opener(self.opener)
	
	def get(self, url, headers={}):
		"""HTTP GET
	
		url should be a string containing a valid URL.
		headers should be a dictionary
		"""
		request = urllib.request.Request(url, headers=headers)
		return self.execute_request(request)
	
	def post(self, url, data=None, headers={}):
		"""HTTP POST
	
		url should be a string containing a valid URL.
		data should be a url-encodable dictionary
		headers should be a dictionary
		"""
		if data is None:
			postdata = None
		else:
			postdata = urllib.parse.urlencode(data).encode(encoding='utf_8')
		request = urllib.request.Request(url, postdata, headers)
		return self.execute_request(request)
	
	def execute_request(self, request):
		times = 0
		while True:
			try:
				response = self.opener.open(request)
				response.status_code = response.getcode()
				response.data = response.read()
				self.cookie_jar.save(ignore_discard=True, ignore_expires=True)
				return response
			except urllib.error.URLError as e:
				times += 1
				print(e)
				if times > 5:
					return None
	#( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
	def set_cookie(self, name, value, expires=0, path='/', domain='.qq.com', secure=False, httponly=False):
		expires = int(time.time() + 86400)
		# 					version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest, rfc2109=False
		c = http.cookiejar.Cookie(0, name, value, '80', False, domain, False, False, path, False, secure, expires, False, None, None, None, rfc2109=False)
		self.cookie_jar.set_cookie(c)
	
	def __del__(self):
		self.cookie_jar.save(ignore_discard=True, ignore_expires=True)
